package com.mrjy.common.qtz;

import com.mrjy.common.entity.CoursePackageInfo;
import com.mrjy.common.entity.CoursePackageVip;
import com.mrjy.common.entity.SolrEntity;
import com.mrjy.common.entity.SubscriptionInfo;
import com.mrjy.common.entity.VideoInfo;
import com.mrjy.common.solr.SolrServerClient;
import com.mrjy.common.thread.ThreadTask;
import com.mrjy.common.thread.TimingThreadPool;
import com.mrjy.common.util.SolrUtil;
import com.mrjy.coursepackage.dao.ICoursePackageInfoDao;
import com.mrjy.coursepackage.dao.ICoursePackageVideoRelDao;
import com.mrjy.coursepackage.dao.ICoursePackageVipDao;
import com.mrjy.coursepackage.dto.CoursePackageInfoDTO;
import com.mrjy.coursepackage.dto.CoursePackageVideoRelDTO;
import com.mrjy.coursepackage.dto.CoursePackageVipDTO;
import com.mrjy.maintain.dao.ISubscriptionInfoDao;
import com.mrjy.maintain.dao.IUserInfoDao;
import com.mrjy.video.dao.IVideoInfoDao;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 定时检测 新上的视频资源
 *
 * @author csshui
 * @date 2017-12-18
 */
public class VideoListJob {
    public static Integer counter_v = 0;
    public static Integer counter_c = 0;

    private static Logger logger = Logger.getLogger(VideoListJob.class);
    @Resource
    private IVideoInfoDao videoInfoDao;
    @Resource
    private ISubscriptionInfoDao subscriptionInfoDao;
    @Resource
    private ICoursePackageInfoDao coursePackageInfoDao;
    @Resource
    private ICoursePackageVipDao coursePackageVipDao;
    @Resource
    private ICoursePackageVideoRelDao coursePackageVideoRelDao;
    @Autowired
	private SolrServerClient solrServerClient;
	@Autowired
	private IUserInfoDao userInfoDao;
    /**
     * @param
     * @Description: 任务执行获取 token
     */
    @SuppressWarnings("unchecked")
    public void doJob() {
        Calendar calendar = Calendar.getInstance();
        int HOUR_OF_DAY = calendar.get(Calendar.HOUR_OF_DAY);

        if (HOUR_OF_DAY == 0) {
            counter_v = 0;
            counter_c = 0;
        }

        synchronized (VideoListJob.counter_v) {
            logger.debug("视频上架处理 ：=================================>");
            VideoInfo videoInfo = new VideoInfo();
            videoInfo.setReleaseFlag(1);
            videoInfo.setDisableFlag(0);
            List<VideoInfo> list = videoInfoDao.queryList(videoInfo);
            long currentTimeMillis = System.currentTimeMillis();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (VideoInfo info : list) {
                String releaseTimeString = info.getReleaseTimeString();
                try {
                    Date parse = formatter.parse(releaseTimeString);
                    long releaseTime = parse.getTime();
                    if (releaseTime < currentTimeMillis) {
                        info.setReleaseFlag(0);
                        int result = videoInfoDao.updateById(info);
                        //发布成功后添加到solr搜索引擎去
                        if(result == 1){
                        	//添加索引
        					SolrEntity entity = new SolrEntity();
        					entity.setId("video_"+info.getId());
        					entity.setVideoId(info.getId());
        					entity.setVideoName(info.getVideoName());
        					entity.setVideoDesc(info.getVideoDesc());
        					entity.setVideoTypes(SolrUtil.formatVideoTypes(info.getTypeIds()));
        					entity.setVideoTeacher(userInfoDao.queryById(info.getUserId()).getUserName());
        					entity.setCoverUrl(videoInfo.getCoverUrl());
        	        		try {
								solrServerClient.add(entity);
							} catch (Exception e) {
								e.printStackTrace();
							}
                        }
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }

        //通知时间：定时发布 早上10:00；晚上20:00 --------- 0 0 0/1 * * ? ||
        if (HOUR_OF_DAY == 10 || HOUR_OF_DAY == 20) {
            logger.debug(" 检测 新上的视频资源 ：=================================>");
            VideoInfo videoInfo = new VideoInfo();
            videoInfo.setAnnouncementFlag(1);
            videoInfo.setDisableFlag(0);
            List<VideoInfo> list = videoInfoDao.queryList(videoInfo);
            long currentTimeMillis = System.currentTimeMillis();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            CoursePackageInfo coursePackageInfo = new CoursePackageInfo();
            coursePackageInfo.setAnnouncementFlag(1);
            coursePackageInfo.setDisableFlag(0);
            coursePackageInfo.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            List<CoursePackageInfoDTO> cList = coursePackageInfoDao.queryList(coursePackageInfo);


            if (null != list && list.size() > 0 && null != cList && cList.size() > 0) {
                CoursePackageVideoRelDTO dto = new CoursePackageVideoRelDTO();
                dto.setCoursePackageId(cList.get(0).getId());
                dto.setVideoId(list.get(0).getId());
                CoursePackageVideoRelDTO coursePackageVideoRelDTO = coursePackageVideoRelDao.selectByCoursePackageIdAndVideoId(dto);
                if (coursePackageVideoRelDTO != null) {
                    counter_c = 1;
                }
            }

            /*
             * 发送微课上新通知
             */
            synchronized (VideoListJob.counter_v) {
                if (null!=list && list.size()>0) {
                    if (counter_v >= 1) {
                        //0 1 2
                        logger.warn("counter_v 总数已经超过预警值");
                        for (VideoInfo info : list) {
                            info.setAnnouncementFlag(0);
                            videoInfoDao.updateById(info);
                        }
                        //都设置为 已通知， 再return
                        return;
                    }
                    VideoInfo info = list.get(0);
                    try {
                        String announcementTime = info.getAnnouncementTimeStr();
                        Date parse = formatter.parse(announcementTime);
                        long announcementTimeLong = parse.getTime();
                        if (announcementTimeLong < currentTimeMillis) {
                            SubscriptionInfo subscriptionInfo = new SubscriptionInfo();
                            //所有人员的订阅
                            subscriptionInfo.setTypeId(2);
                            subscriptionInfo.setTeacherId(info.getUserId());
                            List<SubscriptionInfo> allDealSubs = subscriptionInfoDao.queryBySubUser(subscriptionInfo);

                            for (SubscriptionInfo subscriptionInfo1 : allDealSubs) {
                                try {
                                    if (info.getId() == null || info.getReleaseTimeString() == null || info.getVideoName() == null
                                            || subscriptionInfo1.getUserId() == null || subscriptionInfo1.getWeixinOpenid() == null) {
                                        continue;
                                    } else {
                                        // 产生一个任务，并将其加入到线程池
                                        ThreadTask threadTask = ThreadTask.clonePolyInfo(info.getId(), null, info.getTypeName(), info.getUserName()
                                                , info.getReleaseTimeString(), info.getVideoName(), null, subscriptionInfo1.getUserName(), subscriptionInfo1.getWeixinOpenid()
                                                , info.getDuration(), 1,info.getNoticeTitleDesc(),info.getNoticeFootDesc());
                                        TimingThreadPool.pool.execute(threadTask);
                                        logger.debug("微信模板消息发送成功 ==========> 已向" + subscriptionInfo1.getWeixinOpenid() + "用户推送微信通知");
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                } finally {
                                    info.setAnnouncementFlag(0);
                                    videoInfoDao.updateById(info);
                                }
                            }
                        }
                        logger.debug(" 检测 新上的视频资源 ：=================================>  执行成功");
                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.debug(" 检测 新上的视频资源 ：=================================>  执行失败");
                    }
                    counter_v++;
                }
            }
            /*
             * 发送课程包上新通知
             */
            synchronized (VideoListJob.counter_c) {
                if (null != cList && cList.size() > 0) {
                    if (counter_c >= 1) {
                        //0 1 2
                        logger.warn("counter_c 总数已经超过预警值");
                        for (CoursePackageInfoDTO cInfo : cList) {
                            cInfo.setAnnouncementFlag(0);
                            coursePackageInfoDao.updateById(cInfo);
                        }
                        //都设置为 已通知， 再return
                        return;
                    }
                    CoursePackageInfoDTO cInfo = cList.get(0);
                    try {
                        List<SubscriptionInfo> allDealSubs = new ArrayList<>();

                        //课程包上新通知，只推送给购买了该课程包的人
                        if (StringUtils.isNotBlank(cInfo.getUpdateTimeString())) {
                            CoursePackageVip vip = new CoursePackageVip();
                            vip.setCoursePackageId(cInfo.getId());
                            List<CoursePackageVipDTO> payerList = coursePackageVipDao.queryWhoPayByCoursePackageId(vip);
                            for (CoursePackageVipDTO dto : payerList) {
                                SubscriptionInfo sub = new SubscriptionInfo();
                                sub.setUserId(dto.getUserId());
                                sub.setWeixinOpenid(dto.getWeixinOpenid());
                                allDealSubs.add(sub);
                            }
                        } else {
                            SubscriptionInfo subscriptionInfo = new SubscriptionInfo();
                            //所有人员的订阅
                            subscriptionInfo.setTypeId(2);
                            allDealSubs = subscriptionInfoDao.queryBySubUser(subscriptionInfo);
                        }

                        for (SubscriptionInfo subscriptionInfo1 : allDealSubs) {
                            try {
                                if (cInfo.getId() == null || cInfo.getCoursePackageName() == null
                                        || subscriptionInfo1.getUserId() == null || subscriptionInfo1.getWeixinOpenid() == null) {
                                    continue;
                                } else {
                                    // 产生一个任务，并将其加入到线程池
                                    TimingThreadPool.pool.execute(ThreadTask.clonePolyInfo(null, cInfo.getId(), cInfo.getCoursepackageTypes()
                                            , cInfo.getUserName(), cInfo.getCreateTimeString(), null
                                            , cInfo.getCoursePackageName(), subscriptionInfo1.getUserName()
                                            , subscriptionInfo1.getWeixinOpenid(), cInfo.getUpdateTimeString()
                                            , 2,null,null));
                                    logger.debug("微信模板消息发送成功 ==========> 已向" + subscriptionInfo1.getWeixinOpenid() + "用户推送微信通知");
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            } finally {
                                cInfo.setAnnouncementFlag(0);
                                coursePackageInfoDao.updateById(cInfo);
                            }
                        }
                        logger.debug(" 检测 新上架的课程包资源 ：=================================>  执行成功");
                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.debug(" 检测 新上架的课程包资源 ：=================================>  执行失败");
                    }
                    counter_c++;
                }
            }
        }
    }
}